package middleware

import (
	"common"
	"common/json_response"
	"common/zapx"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
)

// CheckAuth 用户身份检查中间件
func CheckAuth(forceLogin bool) gin.HandlerFunc {
	return func(context *gin.Context) {
		response := json_response.NewJsonHttpResponse(context)
		token := context.GetHeader("Token")
		if token == "" {
			if !forceLogin {
				return
			}
			response.SetCode(json_response.CODE_UNAUTHORIZED).SetStatusCode(http.StatusUnauthorized).SetMsg("未授权").Send()
			context.Abort()
			return
		}
		//解析 token
		claims, err := common.CheckJwtToken(token)
		if err != nil {
			if !forceLogin {
				return
			}
			response.SetCode(json_response.CODE_UNAUTHORIZED).SetStatusCode(http.StatusUnauthorized).SetMsg("未授权").Send()
			context.Abort()
			return
		}
		//查询用户
		userId := claims.ID
		parseUserId, err := strconv.Atoi(userId)
		if err != nil {
			if !forceLogin {
				return
			}
			zapx.Logger.Error("转换用户id失败", zap.Error(err))
			response.SetCode(json_response.CODE_ERROR).SetMsg("系统错误").Send()
			context.Abort()
			return
		}
		context.Set("USER_ID", int32(parseUserId))
		context.Next()
	}
}
